import React, { useState } from 'react'
import { TextInput, StyleProp, TextStyle } from 'react-native'
import { isMoney } from 'utils/validate'
import { formatMoney } from 'utils'

export interface InputNumberProps {
	style?: StyleProp<TextStyle>
	isMoney?: boolean
	editable?: boolean
	defaultValue: number
	upperLimit: number
	lowerLimit: number
	onChange: (value: string) => void
}

const InputNumber: React.FC<InputNumberProps> = props => {
	const [value, setValue] = useState<string>(`${props.defaultValue}`)
	return (
		<TextInput
			style={props.style}
			keyboardType={props.editable ? 'decimal-pad' : 'default'}
			editable={props.editable}
			onChangeText={text => {
				text = text.replace(/[^\d.]/g, '')
				text = text.replace(/[^\d.]/g, "");
				//必须保证第一位为数字而不是. 
				text = text.replace(/^\./g, "");
				//保证只有出现一个.而没有多个. 
				text = text.replace(/\.{2,}/g, ".");
				//保证.只出现一次，而不能出现两次以上 
				text = text.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
				console.log('1111', text)
				let numberText = Number(text)
				if (numberText) {
					if (numberText < props.lowerLimit) {
						text = props.lowerLimit.toString()
					} else if (numberText > props.upperLimit) {
						text = props.upperLimit.toString()
					}
					if (props.isMoney) {
						if (isMoney(text)) {
							setValue(text)
							props.onChange(text)
						}
						return
					}
				}
				setValue(text)
				props.onChange(text)
			}}
			value={value}
		/>
	)
}

export default InputNumber
